package io.renren.utils;

import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件生成器  工具类
 * 主要生成 word版、excel版的数据库设计说明书模板
 *
 * @author huangjiang <huangjiang1026@gmail.com>
 * @date 2020-02-27 11:39
 */
public class FileUtils {

    /**
     * 设置velocity资源加载器
     */
    public static void resourceLoader() {
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
    }

    /**
     * 渲染模板，合并数据，写入到ZIP流
     *
     * @param zip      zip流
     * @param context  上下文
     * @param template 模板
     * @param fileName 文件名
     * @param errorMsg 错误信息
     */
    public static void templateFileWriteToZip(ZipOutputStream zip,
                                              VelocityContext context,
                                              String template,
                                              String fileName,
                                              String errorMsg) {
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, "UTF-8");
        tpl.merge(context, sw);

        try {
            // 添加到zip
            zip.putNextEntry(new ZipEntry(fileName));
            IOUtils.write(sw.toString(), zip, "UTF-8");
            zip.closeEntry();
        } catch (IOException e) {
            throw new RRException(errorMsg, e);
        } finally {
            IOUtils.closeQuietly(sw);
        }
    }

    /**
     * 设置二进制流的响应数据
     *
     * @param response 响应
     * @param data     数据
     * @param fileName 文件名
     * @throws IOException IO异常
     */
    public static void setByteResponse(HttpServletResponse response, byte[] data, String fileName)
            throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

}
